<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<style>
    #btn {
        width: 100px;
        height: 50px;
        background: coral;
        position: fixed;
        top: 0;
    }
</style>
<head>
    <script type="text/javascript">
        let c, ctx, myImage;

        function displayImage() {
            myImage = new Image();
            myImage.src ="../JavaScript_Study/assets/imgs/山019.jpg";
            c = document.getElementById("myCanvas");
            if (c.getContext) {
                ctx = c.getContext("2d");
                myImage.onload = function () {
                    ctx.drawImage(myImage, 0, 0);
                }
            }
        }

        //colorArr 替换后的颜色
        // 替换前的颜色
        function getColorData(colorArr, color2) {
            imageD = ctx.getImageData(0, 0, myImage.width, myImage.height);
            let pdata = imageD.data;
            for (let j = 0; j < pdata.length; j += 4) {
                if (pdata[j] === color2[0]) pdata[j] = colorArr[0];
                if (pdata[j + 1] === color2[1]) pdata[j + 1] = colorArr[1];
                if (pdata[j + 2] === color2[2]) pdata[j + 2] = colorArr[2];
            }
            ctx.putImageData(imageD, 0, 0);
        }

        function colorChange() {
            // rgb颜色
            getColorData([102, 51, 153], [95, 170, 129]);
        }

    </script>
</head>
<body onload="displayImage()">
<p>原始图片：</p>
<img id="myPhoto" src="../JavaScript_Study/assets/imgs/山019.jpg" style = "width:600px;height:400px">
<p>Canvas图片：</p>
<canvas id="myCanvas" width="200" height="200"></canvas>
<button id="btn" onclick="colorChange()">变颜色啦！</button>
</body>
</html>